﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MultiDAQ_Analysis.Calculation.Calculators;
using MultiDAQ_Analysis.Calculation.Interfaces;
using MultiDAQ_Analysis.Calculation.Parameters;
using MultiDAQ_Analysis.Calculation.Results;
using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;

namespace MultiDAQ_Analysis.Calculation.Calculators
{
    public class StandardSourceEfficiencyCalculator : BaseMeasurementCalculator
    {
        public override string MeasurementType => "StandardSourceEfficiency";
        public override Type ParameterType => typeof(StandardSourceParameters);

        protected override async Task ProcessSingleRound(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            // 标准源效率测量单轮处理：记录数据
            foreach (var kvp in context.RawData)
            {
                int channelIndex = kvp.Key;
                var (alpha, beta) = kvp.Value;

                result.ChannelResults[channelIndex] = new ChannelCalculationResult
                {
                    ChannelIndex = channelIndex,
                    AlphaResult = alpha,
                    BetaResult = beta,
                    //IsValid = alpha > 0 && beta > 0
                };
            }

            await Task.CompletedTask;
        }

        protected override async Task ProcessFinalCalculation(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            var parameters = context.Parameters as StandardSourceParameters;
            if (parameters == null) throw new ArgumentException("标准源效率测量参数类型错误");

            foreach (var channelHistory in context.HistoryData)
            {
                int channelIndex = channelHistory.Key;
                var measurements = channelHistory.Value;

                if (measurements.Count > 0)
                {
                    double alphaAvg = measurements.Average(m => m.alpha);
                    double betaAvg = measurements.Average(m => m.beta);
                    var (alphaBg, betaBg) = GetBackgroundData(channelIndex);

                    // 根据PDF公式计算标准源效率
                    // es(α) = [Rs(α) - Rb(α)] / [As(α)×Ms(α)] × 1000× 100%
                    double netAlphaRate = alphaAvg - alphaBg;
                    double netBetaRate = betaAvg - betaBg;

                    double alphaSpecActivity = parameters.AlphaSpecificActivity.GetValueOrDefault(channelIndex, 12.5);
                    double betaSpecActivity = parameters.BetaSpecificActivity.GetValueOrDefault(channelIndex, 14.4);
                    double sourceMass = parameters.SourceMass.GetValueOrDefault(channelIndex, 20.0);

                    // 效率计算（转换为小数形式）
                    double alphaEfficiency = (netAlphaRate / (alphaSpecActivity * sourceMass)) * 1000 * 100 / 100; // 最后除100转为小数
                    double betaEfficiency = (netBetaRate / (betaSpecActivity * sourceMass)) * 1000 * 100 / 100;

                    result.ChannelResults[channelIndex] = new ChannelCalculationResult
                    {
                        ChannelIndex = channelIndex,
                        AlphaResult = alphaEfficiency,
                        BetaResult = betaEfficiency,
                        AlphaUncertainty = CalculateStandardDeviation(measurements.Select(m => m.alpha - alphaBg).ToList()),
                        BetaUncertainty = CalculateStandardDeviation(measurements.Select(m => m.beta - betaBg).ToList()),
                        //IsValid = netAlphaRate > 0 && netBetaRate > 0,
                        ExtendedResults = new Dictionary<string, double>
                        {
                            ["AlphaSpecificActivity"] = alphaSpecActivity,
                            ["BetaSpecificActivity"] = betaSpecActivity,
                            ["SourceMass"] = sourceMass,
                            ["NetAlphaRate"] = netAlphaRate,
                            ["NetBetaRate"] = netBetaRate
                        }
                    };
                }
            }

            await Task.CompletedTask;
        }

        protected override async Task SaveChannelResult(int channelIndex, ChannelCalculationResult channelResult, MeasurementCalculationResult overallResult)
        {
            var channelData = ChannelDataManager.LoadChannelData(channelIndex);

            channelData.WorkConditions.AlphaStandardEfficiency = channelResult.AlphaResult;
            channelData.WorkConditions.BetaStandardEfficiency = channelResult.BetaResult;
            channelData.LastModified = DateTime.Now;

            if (channelData.MeasurementResults == null)
                channelData.MeasurementResults = new MeasurementResultData();

            channelData.MeasurementResults.StandardSourceMeasurement = new StandardSourceMeasurementResult
            {
                AlphaEfficiency = channelResult.AlphaResult,
                BetaEfficiency = channelResult.BetaResult,
                MeasurementTime = DateTime.Now
            };

            ChannelDataManager.SaveChannelData(channelIndex, channelData);
            await Task.CompletedTask;
        }
    }
}